import {
  accountLoginRequest,
  requestUserMenusByRoleId
} from '@/service/login/login'
import { IAccount } from '@/service/login/type'
import { Module } from 'vuex'
import { IRootState } from '../type'
import { ILoginState } from './type'
import LocalCache from '@/utils/cache'
import { mapMenusToRoutes } from '@/utils/map-menus'
import router from '@/router'
import localCache from '@/utils/cache'
const login: Module<ILoginState, IRootState> = {
  namespaced: true, //命名空间
  state: {
    userInfo: '',
    // token: '',
    userMenus: ''
  },
  mutations: {
    changeUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    changeUserMenus(state, userMenus: any) {
      state.userMenus = userMenus
      const routes = mapMenusToRoutes(userMenus)

      // 将routes => router.main.children
      routes.forEach((route) => {
        router.addRoute('main', route)
      })
      console.log(router)
    }
  },
  getters: {},
  actions: {
    //点击登录状态
    async accountLoginAction({ commit }, payload: IAccount) {
      const loginResult = await accountLoginRequest(payload)

      const { status, data } = loginResult
      //缓存到本地
      LocalCache.setCache('userInfo', data)
      //存到vuex
      commit('changeUserInfo', data)
      //登录成功后获取菜单树
      if (status == 200) {
        const menusResult = await requestUserMenusByRoleId()

        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        const { status, data } = menusResult
        //缓存到本地
        LocalCache.setCache('userMenus', data)
        //存到vuex
        commit('changeUserMenus', data)
        // 4.跳到首页
        router.push('/main/analysis/home')
      }
    },
    //已登录状态
    loadLocalLogin({ commit }) {
      const userInfo = localCache.getCache('userInfo')
      if (userInfo) {
        commit('changeUserInfo', userInfo)
      }
      const userMenus = localCache.getCache('userMenus')
      if (userMenus) {
        commit('changeUserMenus', userMenus)
      }
    }
  }
}

export default login
